layui.define(['jquery','layer', 'table'], function(exports) {
    "use strict";

    var MOD_NAME = 'backend',
        layer = layui.layer,
        table = layui.table,
        $ = layui.jquery;

    var Backend = {
        api : {
            events: {
                //请求成功的回调
                onAjaxSuccess: function (ret, onAjaxSuccess) {
                    var data = typeof ret.data !== 'undefined' ? ret.data : null;
                    var msg = typeof ret.msg !== 'undefined' && ret.msg ? ret.msg : '未知错误';

                    if (typeof onAjaxSuccess === 'function') {
                        var result = onAjaxSuccess.call(this, data, ret);
                        if (result === false)
                            return;
                    }
                    layer.msg(msg,{icon:1,time:1000});
                },
                //请求错误的回调
                onAjaxError: function (ret, onAjaxError) {
                    var data = typeof ret.data !== 'undefined' ? ret.data : null;
                    if (typeof onAjaxError === 'function') {
                        var result = onAjaxError.call(this, data, ret);
                        if (result === false) {
                            return;
                        }
                    }
                    layer.confirm(ret.msg, {icon: 3, title:'警告'}, function(index){
                        layer.close(index);
                    });
                },
                //服务器响应数据后
                onAjaxResponse: function (response) {
                    try {
                        var ret = typeof response === 'object' ? response : JSON.parse(response);
                        if (!ret.hasOwnProperty('code')) {
                            $.extend(ret, {code: -2, msg: response, data: null});
                        }
                    } catch (e) {
                        var ret = {code: -1, msg: e.message, data: null};
                    }
                    return ret;
                },
                // 点击弹窗时间
                open : function () {
                    $(".alert-open").click(function () {
                        var doc = $(this);
                        var title = doc.data('title');
                        var url = doc.data('url');
                        var option = doc.data('option');
                        Backend.api.open(url,title, option);
                    });
                },
                ajax : function () {
                    $(".api-ajax").click(function () {
                        var doc = $(this);
                        var url = doc.data('url');
                        var type = doc.data('type') == undefined ? 'get' : doc.data('type');
                        var success = function () {
                            var callback = doc.data('callback');
                            if (callback != undefined) {
                                callback = eval('(' + callback + ')');
                                if (typeof callback == 'function') {
                                    return callback();
                                }
                            }
                        }
                        Backend.api.ajax({
                            url : url,
                            type : type
                        }, success)
                    });
                }
            },
            ajax: function (options, success, error) {
                options = typeof options === 'string' ? {url: options} : options;
                var index;
                if (typeof options.loading === 'undefined' || options.loading) {
                    index = layer.load(options.loading || 0);
                }
                options = $.extend({
                    type: "POST",
                    dataType: "json",
                    success: function (ret) {
                        ret = Backend.api.events.onAjaxResponse(ret);
                        if (ret.code === 1) {
                            Backend.api.events.onAjaxSuccess(ret, success);
                        } else {
                            Backend.api.events.onAjaxError(ret, error);
                        }
                    },
                    error: function (xhr) {
                        var ret = {code: xhr.status, msg: xhr.statusText, data: null};
                        Backend.api.events.onAjaxError(ret, error);
                    },
                    complete: function (xhr) {
                        index && layer.close(index);
                    }
                }, options);
                return $.ajax(options);
            },
            //打开一个弹出窗口
            open: function (url, title, options) {
                title = options && options.title ? options.title : (title ? title : "");
                var area = [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 600 ? '600px' : '95%'];
                options = $.extend({
                    type: 2,
                    title: title,
                    shadeClose: true,
                    shade: false,
                    maxmin: true,
                    moveOut: true,
                    area: area,
                    content: url,
                    success: function (layero, index) {
                        var that = this;
                        //存储callback事件
                        $(layero).data("callback", that.callback);
                        if ($(layero).height() > $(window).height()) {
                            //当弹出窗口大于浏览器可视高度时,重定位
                            layer.style(index, {
                                top: 0,
                                height: $(window).height()
                            });
                        }
                    }
                }, options ? options : {});
                if ($(window).width() < 480 || (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream && top.$(".tab-pane.active").size() > 0)) {
                    options.area = [top.$(".tab-pane.active").width() + "px", top.$(".tab-pane.active").height() + "px"];
                    options.offset = [top.$(".tab-pane.active").scrollTop() + "px", "0px"];
                }
                return layer.open(options);
            },
            //关闭窗口并回传数据
            close: function (data = null) {
                var index = parent.layer.getFrameIndex(window.name);
                var callback = parent.layui.$("#layui-layer" + index).data("callback");
                //再执行关闭
                parent.layer.close(index);
                //再调用回传函数
                if (typeof callback === 'function') {
                    callback.call(undefined, data);
                }
            },
        },
        table : {
            ins: null,
            option : null,
            curd : function (option) {
                Backend.table.option = $.extend({
                    page: true ,
                    skin: 'line',
                    parseData : function (res) {
                        return {
                            "code": res.code == 1 ? 0 : res.code, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "count": res.data.total, //解析数据长度
                            "data": res.data.list //解析数据列表
                        };
                    },
                    defaultToolbar: [{
                        title: '刷新',
                        layEvent: 'refresh',
                        icon: 'layui-icon-refresh',
                    }, 'filter', 'print']
                }, option)
                // 初始化表格
                Backend.table.ins = table.render(Backend.table.option);

                // 监听表格 点击事件
                table.on('tool(' + Backend.table.option.id + ')', function(obj){
                    var clickObj = $(this);
                    var functionName = "event_tool_" + obj.event;
                    Backend.table.commonBindEvent(clickObj, obj, functionName);
                });

                // 监听头部事件
                table.on('toolbar(' + Backend.table.option.id + ')', function(obj){
                    var clickObj = $(this);
                    var functionName = "event_toolbar_" + obj.event;
                    Backend.table.commonBindEvent(clickObj, obj,functionName);
                });
                return Backend.table.ins;
            },
            commonBindEvent: function (doc, obj, defaultFunctionName) {
                var title = doc.data('title');
                var url = doc.data('url');
                switch (obj.event) {
                    case "add":
                        Backend.table.show(url, title);
                        break;
                    case "edit":
                        url = url + (url.indexOf("?") != -1 ? '&id=' : '?id=') + obj.data.id;
                        Backend.table.show(url, title);
                        break;
                    case "remove":
                        Backend.table.del(url, obj);
                        break;
                    case "batchRemove":
                        Backend.table.batchDel(url, obj);
                        break;
                    default:
                        try {
                            if(typeof(eval(defaultFunctionName)) == "function") {
                                eval(defaultFunctionName+ "(obj);")
                            }
                        } catch(e) {
                            // layui.hint().error("未找到事件方法" + defaultFunctionName + ":" + e);
                        }
                }
            },
            show : function (url, title) {
                Backend.api.open(url, title, {
                    callback : function () {
                        table.reload(Backend.table.option.id);
                    }
                });
            },
            del : function (url, obj) {
                layer.confirm('确定要删除？', {icon: 3, title:'提示'}, function(index){
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: url,
                        dataType:'json',
                        type:'post',
                        data : {ids : [obj.data.id]},
                        success:function(result){
                            layer.close(loading);
                            if(result.code == 1){
                                layer.msg(result.msg,{icon:1,time:1000},function(){
                                    table.reload(Backend.table.option.id);
                                });
                            }else{
                                layer.msg(result.msg,{icon:2,time:1000});
                            }
                        }
                    })
                });
            },
            batchDel : function (url, obj) {
                let data = table.checkStatus(obj.config.id).data;
                if(data.length === 0){
                    layer.msg("未选中数据",{icon:3,time:1000});
                    return false;
                }
                let ids = [];
                for(let i = 0;i<data.length;i++){
                    ids.push(data[i].id);
                }
                layer.confirm('确定要删除' + ids.length + '条数据吗?', {icon: 3, title:'提示'}, function(index){
                    layer.close(index);
                    Backend.api.ajax({
                        url : url,
                        type : 'post',
                        data : {ids : ids}
                    }, function (data, ret) {
                        layer.msg(ret.msg,{icon:1,time:1000},function(){
                            table.reload(Backend.table.option.id);
                        });
                    })
                });
            },
        },
        // 公共事件
        common : {
            bindevent: function () {
                // 点击弹窗事件
                Backend.api.events.open();
                // 点击ajax请求事件
                Backend.api.events.ajax();
            }
        }
    }

    exports(MOD_NAME,Backend);
});
